//------------------------------------------------------------------------------
// Copyright (c) 2007 Ste Brennan (dnaide.com)
// Licensed under the MIT (MIT-LICENSE.txt)
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;

using DNAide.Core;

namespace DNAide.Web
{
	/// <summary>
	/// Property value that will inspect the query string for value
	/// and return if found, otherwise a default instance of T 
	/// or an instance of T created via a delegate.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public partial class FormProperty<T>
	{
		private readonly string _key;
		private T _default;
		private readonly Creator<T> _creator;
		private readonly object _lock = new object();
		private bool _created;

		/// <summary>
		/// Key to reference value in query string.
		/// </summary>
		public string Key
		{
			get { return _key; }
		}

		/// <summary>
		/// Query string value if found, otherwise instance from creator
		/// if available or default value.
		/// </summary>
		public T Value
		{
			get
			{
				if (HttpContext.Current.Request.Form[_key] == null)
				{
					if (_creator != null && !_created)
					{
						lock (_lock)
						{
							_default = _creator();
							_created = true;
						}
					}

					return _default;
				}
				else
					return CastAide.As(HttpContext.Current.Request.Form[_key], _default);
			}
		}

		/// <summary>
		/// Will use default value of type.
		/// </summary>
		/// <param name="key">Key to reference in query string</param>
		public FormProperty(string key)
		{
			_key = key;
			_default = default(T);
		}

		/// <summary>
		/// Will use specified default value.
		/// </summary>
		/// <param name="key">Key to reference in query string</param>
		/// <param name="defaultValue">Default value to use if query string value empty</param>
		public FormProperty(string key, T defaultValue)
		{
			_key = key;
			_default = defaultValue;
		}

		/// <summary>
		/// Will use specified creator delegate
		/// </summary>
		/// <param name="key">Key to reference in query string</param>
		/// <param name="creator">Default instance as supplied by creator delegate</param>
		public FormProperty(string key, Creator<T> creator)
		{
			_key = key;
			_creator = creator;
		}
	}
}
